package com.jiuyou.clientController.sendNotice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.sendNotice.domain.SendNotice;
import com.ruoyi.sendNotice.domain.TemplateData;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 *
 *
 * @author fanqingyu
 * @date 2025-05-12
 */
@RestController
@RequestMapping("/client/sendNotice")
public class SendNoticeController extends BaseController
{

    @RequestMapping("/sendNotice")
    public String sendNotice(@RequestBody SendNotice sendNotice) throws Exception {
        if(sendNotice == null){
            return "";
        }
        String appId = "wx72f6cd0003875634";
        String appSecret = "c8b64ac6b956ddb6ee88a0891e45cd3f";
        String templateId = "H5KYpoZZWnfzVzjlo5XmGmwySqgispIl8UaR7SZR6aQ";
        String openId = sendNotice.getOpenId();
        String toUrl = sendNotice.getToUrl();

        RestTemplate restTemplate = new RestTemplate();
        //这里简单起见我们每次都获取最新的access_token（时间开发中，应该在access_token快过期时再重新获取）
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + getAccessToken(appId,appSecret);
        //拼接推送的模版
        SendNotice wxMssVo = new SendNotice();
        wxMssVo.setOpenId(openId);//用户的openid（要发送给那个用户，通常这里应该动态传进来的）
        wxMssVo.setTemplateId(templateId);//订阅消息模板id
        wxMssVo.setPage("pages/index/index");

        Map<String, TemplateData> m = new HashMap<>(3);
        m.put("date4", new TemplateData("小程序入门课程"));
        m.put("thing20", new TemplateData("杭州浙江大学"));
        m.put("thing16", new TemplateData("第一章第一节"));
        m.put("thing7", new TemplateData("第一章第一节"));
        wxMssVo.setData(m);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, wxMssVo, String.class);
        return responseEntity.getBody();
    }



    @RequestMapping("/getAccessToken")
    public String getAccessToken(String appId, String appSecret) throws Exception {
        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> params = new HashMap<>();
        params.put("APPID", appId);  //
        params.put("APPSECRET", appSecret);  //
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}", String.class, params);
        String body = responseEntity.getBody();
        JSONObject object = JSON.parseObject(body);
        String Access_Token = object.getString("access_token");
        String expires_in = object.getString("expires_in");
        System.out.println("有效时长expires_in：" + expires_in);
        return Access_Token;
    }

    /**
     * 消息推送配置 验证请求的合法性
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     */
    @RequestMapping("/checkSignature")
    public boolean checkSignature( String signature, String timestamp, String nonce) {
        // 小程序消息推送自己配置的token
        String[] arr = new String[]{"S9mO0O9IjD4zJdkPP5aHZxru9mYVXy764TDfCfKIAGo", timestamp, nonce};
        // 将token、timestamp、nonce三个参数进行字典序排序
        Arrays.sort(arr);
        // 将排序后的结果拼接成一个字符串
        String content = String.join("", arr);
        try {
            //获取加密工具
            MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
            // 使用SHA-1加密
            byte[] hashBytes = sha1.digest(content.getBytes());
            //将字节数组转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : hashBytes) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            // 将加密后的字符串与微信服务器提供的签名进行对比
            return hexString.toString().equals(signature);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        // 如果签名不匹配，则返回false
        return false;
    }

}
